package com.hanfengyi.course.service.impl;

import com.hanfengyi.course.domain.Course;
import com.hanfengyi.course.domain.CourseDetail;
import com.hanfengyi.course.domain.CourseMarket;
import com.hanfengyi.course.domain.CourseType;
import com.hanfengyi.course.dto.CourseDTO;
import com.hanfengyi.course.mapper.CourseDetailMapper;
import com.hanfengyi.course.mapper.CourseMapper;
import com.hanfengyi.course.mapper.CourseMarketMapper;
import com.hanfengyi.course.query.CourseQuery;
import com.hanfengyi.course.service.ICourseService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hanfengyi.course.temp.CourseNativeSearchQueryBuilder;
import com.hanfengyi.doc.CourseDoc;
import com.hanfengyi.feign.ESFeignClient;
import com.hanfengyi.hrm.AjaxResult;
import com.hanfengyi.hrm.LoginInfo;
import com.hanfengyi.hrm.PageList;
import com.hanfengyi.hrm.UserContext;
import com.hanfengyi.hrm.query.BaseQuery;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hfy
 * @since 2020-02-21
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private ESFeignClient esFeignClient;
    @Override
    public void saveOrUpdate(CourseDTO courseDTO) {
        Course course = courseDTO.getCourse();
        //拿到登录信息
        LoginInfo loginInfo = UserContext.getLoginInfo();
        //保存登录信息
        course.setTenantId(loginInfo.getTenantId());
        course.setTenantName(loginInfo.getTenantName());
        course.setUserId(loginInfo.getUserId());
        course.setUserName(loginInfo.getUserName());
        baseMapper.insert(course);

        CourseDetail courseDetail = courseDTO.getCourseDetail();
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);

        CourseMarket courseMarket = courseDTO.getCourseMarket();
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);
    }

    @Override
    public void offLineCourse(Long id) {
        //1. 根据id查询课程
        Course course = baseMapper.selectById(id);
        //2. 判断课程状态是否是上线状态
        if(course!=null && course.getStatus()==1){
            //3. 删除es中的数据
            AjaxResult ajaxResult = esFeignClient.deleteById(id);
            //es中数据删除成功
            if(ajaxResult.isSuccess()){
                //4. 修改mysql中的课程中的课程状态为下线状态
                course.setStatus(Course.COURSE_OFFLINE);
                baseMapper.updateById(course);
            }
        }else{
            throw new RuntimeException("课程不存在或者课程已处于下线状态");
        }
    }

    @Override
    public void onLineCourse(Long id) {
        //1. 根据id查询课程
        Course course = baseMapper.selectById(id);
        //2. 判断课程状态是否是下线状态
        if(course!=null && course.getStatus()==0){
            //3. 封装CourseDoc对象
            CourseDoc courseDoc = new CourseDoc();
            BeanUtils.copyProperties(course, courseDoc);

            CourseDetail courseDetail = courseDetailMapper.selectById(course.getId());
            BeanUtils.copyProperties(courseDetail, courseDoc);

            CourseMarket courseMarket = courseMarketMapper.selectById(course.getId());
            courseDoc.setChargeName(courseMarket.getCharge().longValue()==1?"收费":"免费");
            BeanUtils.copyProperties(courseMarket, courseDoc);
            //4. 保存到es中
            AjaxResult ajaxResult = esFeignClient.save(courseDoc);
            //es中数据保存成功
            if(ajaxResult.isSuccess()){
                //5. 修改mysql中的课程中的课程状态为上线状态
                course.setStatus(Course.COURSE_ONLINE);
                baseMapper.updateById(course);
            }
        }else{
            throw new RuntimeException("课程不存在或者课程已处于上线状态");
        }


    }

    /**
     * 课程查询
     * @param
     * @return
     */
    @Override
    public PageList<CourseType> queryCourses(CourseQuery courseQuery) {
        System.out.println(courseQuery);
        //1. 封装查询条件
        CourseNativeSearchQueryBuilder courseNativeSearchQueryBuilder = new CourseNativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        if(courseQuery.getProductType()!=null)
        boolQueryBuilder.filter(new TermQueryBuilder("courseTypeId", courseQuery.getProductType()));

        if(courseQuery.getKeyword().length()>0)
        boolQueryBuilder.must(new MatchQueryBuilder("name",courseQuery.getKeyword()));

        if(courseQuery.getPriceMin()!=null && courseQuery.getPriceMax()!=null)
        boolQueryBuilder.filter(new RangeQueryBuilder("price").lte(courseQuery.getPriceMax()).gte(courseQuery.getPriceMin()));

        courseNativeSearchQueryBuilder.withQuery(boolQueryBuilder);

        if(!courseQuery.getSortField().isEmpty()) {
            String sortField = courseQuery.getSortField();
            switch (courseQuery.getSortField()) {
                case "xl":
                    courseNativeSearchQueryBuilder.withSort(new FieldSortBuilder("buyCount").order(SortOrder.DESC));
                    break;
                case "xp":
                    courseNativeSearchQueryBuilder.withSort(new FieldSortBuilder("onlineDate").order(SortOrder.DESC));
                    break;
                case "jg":
                    courseNativeSearchQueryBuilder.withSort(new FieldSortBuilder("price").order(SortOrder.DESC));
                    break;
                case "rq":
                    courseNativeSearchQueryBuilder.withSort(new FieldSortBuilder("viewCount").order(SortOrder.DESC));
                    break;
                default: courseNativeSearchQueryBuilder.withSort(new FieldSortBuilder("price").order(SortOrder.DESC));;
            }
        }
        courseNativeSearchQueryBuilder.withPageable(PageRequest.of(courseQuery.getPage()-1, courseQuery.getRows()));
        //2. 通过fign调用es执行查询，返回结果
        return esFeignClient.searchByQuery(courseNativeSearchQueryBuilder);
    }
}
